import { Grid, SearchBar, SideBar } from 'antd-mobile'
import React, { useEffect, useState, useMemo, useCallback } from 'react'
import style from './index.less'
import { areaList } from '@vant/area-data'
import classnames from 'classnames'
import { tabType, tabThird, getList } from '@/services/Publish'
type Props = {
    showSearch?: boolean;
    onChange?: (value: any) => void
}
interface dataDto {
    id: number;
    menuName: string;
    level: string;
    maxPrice: number;
    minPrice: number;
    list: listDto[]
}
interface listDto {
    id: number,
    name: string
}

export default (props: Props) => {
    const { province_list, city_list } = areaList // 省市区
    const { showSearch, onChange } = props;
    const [activeKey, setActiveKey] = useState("1")
    const [tabs, setTabs] = useState<dataDto[]>([])//种类一级菜单
    const [tabsThird, setTabsThird] = useState<dataDto[]>([])//种类二级菜单
    const [tabsThree, setTabsThree] = useState<dataDto[]>([])//种类三级菜单
    const [searchActive, setSearchActive] = useState<boolean>(false);
    const [species, setSpecies] = useState<string>()
    const [name, setName] = useState<string>()//获取省名或种类一级id
    const [classify, setClassify] = useState<string>("1")//存储种类名称
    const [searchValue, setSearchValue] = useState('');//分类搜索框值
    const [listData, setListData] = useState<listDto[]>([])//获取分类查询信息
    const [listObj, setListObj] = useState({})//省列表
    const [selected, setSelected] = useState<number>();
    const [selectedValue, setSelectedValue] = useState<string>();

    //获取输入框值,并执行查询
    const handleInputChange = useCallback((value: string) => {
        setSearchValue(value)
        if (!value) {
            setListData([])
            return;
        }
        setTimeout(async () => {
            const res = await getList(value)
            setListData(res)
        }, 500)
    }, [searchValue])
    //省市列表
    useEffect(() => {
        const proviceIdArr = Object.keys(province_list)
        const cityIdArr = Object.keys(city_list)
        const obj = proviceIdArr.reduce((result, v) => {
            const partten = v.slice(0, 2)
            const cities = cityIdArr.filter(x => x.slice(0, 2) === partten).map(x => city_list[x])
            cities.unshift('全部');
            result[province_list[v]] = cities
            return result
        }, {})
        setListObj(obj)

    }, [])

    //获取一级菜单
    const getDataFirst = async () => {
        const res = await tabType()
        setTabs(res)
        if (res.length > 0) {
            getDataThird(classify)
        }
    }
    //获取二级、三级菜单
    const getDataThird = useCallback(async (classify: string) => {
        const res = await tabThird(classify)
        setTabsThird(res)
        setTabsThree(res[classify].list)
    }, [])

    useEffect(() => {
        getDataFirst()
    }, [name, classify])

    //获取省市，一级种类选择的值
    const handleChange = (values: string) => {
        setActiveKey(values)
        {
            showSearch ? (
                setClassify(values),
                getDataThird(values)
            ) : (
                setName(values)
            )
        }
    }

    //点击市存市数据
    const handleCityClick = (value: string) => {
        setSelectedValue(value);
        console.log(value);
    };
    //点击三级种类存数据
    const handleMenuClick = (value: string) => {
        setSpecies(value);
        onChange(JSON.parse(JSON.stringify(value)))
        console.log(value);
    };

    //点击搜索结果存储数据
    const handleSearchClick = (value: number) => {
        setSelected(value);
        console.log(value);

    }

    //输入框点击变换界面样式
    const onSearchFocus = useCallback(() => {
        setSearchActive(true);
    }, [searchActive]);

    return (
            <div className={style['top-list']}>
                {showSearch ? (
                    <SearchBar
                        placeholder='请输入关键字'
                        onChange={handleInputChange}
                        showCancelButton
                        value={searchValue}
                        onCancel={() => setSearchActive(false)}
                        onFocus={onSearchFocus}
                        className={style.search}
                    />
                ) : null}
                {searchActive ? (
                    <div className={style.select}>
                        {listData?.length > 0 ? (
                            <div className={style['select-list']}>
                                {listData?.map((item) => (
                                    <div
                                        key={item.id}
                                        className={classnames(style['select-item'], { [style.selected]: selected === item.id })}
                                        onClick={() => handleSearchClick(item.id)}
                                    >
                                        {item.name}
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div>暂时没有匹配道搜索结果</div>
                        )}
                    </div>
                ) : (
                    <div className={style.container}>
                        <div className={style.aa}>
                            <SideBar
                                onChange={handleChange}
                                activeKey={activeKey}
                                className={classnames(style.side, {
                                    [style.width]: true !== showSearch
                                })}
                            >
                                {showSearch ? (tabs?.map((item) => (
                                    <SideBar.Item key={item.id} title={item.menuName} />
                                )))
                                    : (Object.keys(listObj).map(item => (
                                        <SideBar.Item key={item} title={item} />
                                    )))}

                            </SideBar>
                        </div>

                        <div className={style.main}>
                            {showSearch ? (tabsThird?.map((menu) => (
                                <div
                                    key={menu.id}
                                    className={classnames(style.city, { [style.selected]: selectedValue === menu.menuName })}
                                >
                                    <div className={style.menuThird}>{menu?.menuName}</div>
                                    <Grid columns={3} gap={18}>
                                        {tabsThree?.map((item) => (
                                            <Grid.Item
                                                key={item.id}
                                                className={classnames(style.grid, { [style['grid-select']]: species === item.level })}
                                                onClick={() => handleMenuClick(item.level)}
                                                
                                            >
                                                <div className={style['centered-content']}>
                                                    {item.menuName}
                                                </div>
                                            </Grid.Item>
                                        ))}
                                    </Grid>
                                </div>
                            )))
                                : (listObj[name]?.map((item: string) => (
                                    <div
                                        key={item}
                                        className={classnames(style.city, { [style.selected]: selectedValue === item })}
                                        onClick={() => handleCityClick(item)}
                                    >
                                        {item}
                                    </div>
                                )))
                            }
                        </div>
                    </div>
                )}
            </div>
    )
}
